<template>
  <view class="container">
    <view class="tui-flex">
      <image mode="widthFix" :src="bookDetail.cover" style="width:150rpx;" />
      <view
        class="tui-flex-1 tui-flex tui-flex-column tui-align-between"
        style="padding-left:20rpx;"
      >
        <view style="font-weight:bold;font-size:38rpx;">{{
          bookDetail.name || "名称"
        }}</view>
        <view style="color:#aaa;font-size:28rpx;">
          <tui-icon name="people" :size="18" color="#6cc" />
          {{ bookDetail.author || "作者" }}
        </view>
        <view style="color:#ccc;font-size:26rpx;">
          {{ bookDetail.category || "类别" }} ·
          {{ bookDetail.status || "状态" }}
        </view>
      </view>
    </view>
    <view style="margin-top:30rpx;font-size:28rpx;">{{
      bookDetail.description || "简介"
    }}</view>
    <view
      class="tui-flex tui-vertical-center"
      hover-class="tui-white-hover"
      style="padding:20rpx 0;"
      @tap="goCatalog"
    >
      <text style="font-weight:bold;font-size:38rpx;">目录</text>
      <text
        class="tui-flex-1"
        style="color:#bbb;font-size:26rpx;padding-left:20rpx;"
        >{{ bookDetail.latest_chapter_name }}</text
      >
      <text style="color:#888;font-size:28rpx;">{{
        bookDetail.update_time_cover || "更新时间"
      }}</text>
    </view>

    <tui-operation :buttons="operation" @button-click="tapOperation" />

    <tui-page-loading type="spin" :show="loading" />
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { format } from "timeago.js";
import { stringify } from "qs";
import tuiIcon from "@/components/icon/icon.vue";
import tuiOperation from "@/components/operation/operation.vue";
import tuiPageLoading from "@/components/page-loading/page-loading.vue";
import navigateTo from "@/pages/read/navigateTo.js";
import { equalUrl } from "@/utils/util";

export default {
  components: { tuiOperation, tuiIcon, tuiPageLoading },
  data() {
    return {
      source_id: "",
      read_url: "",
      loading: false,
      bookDetail: {},
      addLoading: false
    };
  },
  computed: {
    ...mapState(["bookshelfs"]),
    operation() {
      return [
        {
          text:
            this.bookDetail.inBookshelf == 1
              ? "已加书架"
              : this.bookDetail.inBookshelf
              ? "加备用源"
              : "加入书架",
          disabled: this.bookDetail.inBookshelf == 1,
          loading: this.addLoading
        },
        {
          type: "danger",
          text: this.bookDetail.inBookshelf ? "继续阅读" : "开始阅读",
          loading: false
        }
      ];
    },
    book() {
      return this.bookshelfs.find(
        bs =>
          bs.name == this.bookDetail.name && bs.author == this.bookDetail.author
      );
    }
  },
  onLoad(options) {
    if (!options.source_id || !options.read_url) {
      this.tui.toast("参数缺失");
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000);
    } else {
      this.source_id = options.source_id;
      this.read_url = options.read_url;
      this.init();
    }
  },
  methods: {
    ...mapMutations(["setBookshelfs"]),
    init() {
      this.loading = true;
      this.callFunc({
        name: "bookDetail",
        data: {
          source_id: this.source_id,
          read_url: this.read_url
        }
      })
        .then(res => {
          if (res.result.errMsg == "ok") {
            const bookDetail = res.result.data;
            bookDetail.inBookshelf = this.isInBookshelfs(bookDetail);
            bookDetail.update_time_cover = format(
              bookDetail.update_time,
              "zh_CN"
            );
            this.bookDetail = bookDetail;
          } else {
            this.tui.toast(res.result.errMsg);
          }
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
          this.tui.toast("请求失败，请重试");
          setTimeout(() => {
            uni.navigateBack({
              delta: 1
            });
          }, 1000);
        });
    },
    // 是否在书架中
    isInBookshelfs(item) {
      const book = this.bookshelfs.find(
        bs => bs.name == item.name && bs.author == item.author
      );
      if (!book) {
        return 0;
      }
      if (
        book.source_id == item.source_id &&
        equalUrl(book.read_url, item.read_url)
      ) {
        return 1;
      } else if (
        book.other_sources &&
        book.other_sources.some(
          os =>
            os.source_id == item.source_id &&
            equalUrl(os.read_url, item.read_url)
        )
      ) {
        return 1;
      }
      return -1;
    },
    // 查看目录
    goCatalog() {
      const { source_id, read_url } = this;
      let _id;
      if (this.book) {
        _id = this.book._id;
      }
      uni.navigateTo({
        url: "/pages/catalog/catalog?" + stringify({ source_id, read_url, _id })
      });
    },
    tapOperation(index) {
      if (index == 0) {
        // 加入书架
        this.addLoading = true;
        const {
          name,
          author,
          read_url,
          cover,
          source_id,
          first_chapter_url,
          latest_chapter_url
        } = this.bookDetail;
        this.callFunc({
          name: "addBookshelf",
          data: {
            name,
            author,
            cover,
            source_id,
            read_url,
            latest_chapter_url,
            url: first_chapter_url
          }
        })
          .then(res => {
            // console.log(res);
            if (res.result.errMsg == "ok") {
              const bookshelfs = this.bookshelfs;
              const inBookshelf = this.bookDetail.inBookshelf;
              if (inBookshelf == 0) {
                // 添加书架
                bookshelfs.unshift({
                  ...this.bookDetail,
                  inBookshelf: 1,
                  url: first_chapter_url,
                  read_time: new Date().getTime(),
                  ...res.result.data
                });
              } else if (inBookshelf == -1) {
                // 添加备用源
                bookshelfs.forEach(bs => {
                  if (bs._id == res.result.data._id) {
                    bs.other_sources = res.result.data.other_sources;
                  }
                });
              }
              this.setBookshelfs(bookshelfs);
              this.bookDetail.inBookshelf = 1;
              this.bookDetail._id = res.result.data._id;
            } else {
              this.tui.toast(res.result.errMsg);
            }
            this.addLoading = false;
          })
          .catch(err => {
            this.tui.toast("请求失败，请重试");
            this.addLoading = false;
          });
      } else if (index == 1) {
        if (this.bookDetail.inBookshelf) {
          // 继续阅读
          const bookDetail = this.bookshelfs.find(
            bs =>
              bs.name == this.bookDetail.name &&
              bs.author == this.bookDetail.author
          );
          if (!bookDetail) {
            return;
          }
          const { source_id, read_url, url, page, _id, name } = bookDetail;
          navigateTo("pages/read/read", {
            source_id,
            read_url,
            url,
            page,
            name,
            _id
          });
        } else {
          // 开始阅读
          const {
            source_id,
            read_url,
            first_chapter_url,
            name
          } = this.bookDetail;
          navigateTo("pages/read/read", {
            source_id,
            read_url,
            url: first_chapter_url,
            name
          });
        }
      }
    }
  }
};
</script>

<style>
.container {
  padding: 30rpx;
  box-sizing: border-box;
}
</style>
